package com.kern.academic.controller;

import com.alibaba.fastjson.JSONObject;
import com.kern.academic.bean.ResponseResult;
import com.kern.academic.entity.XUser;
import com.kern.academic.service.IUserService;
import com.kern.academic.util.CommonUtil;
import com.kern.academic.util.JWTUtil;
import com.kern.academic.util.RedisUtil;
import com.wf.captcha.SpecCaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.wf.captcha.base.Captcha.TYPE_ONLY_NUMBER;

/**
 * Created by caoshi at 10:51 2021-06-26
 */
@RestController
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IUserService userService;

    public static final String captcha_key_suffix = "capt:";

    /**
     * 获取验证码
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping("/captcha")
    public ResponseResult captcha(HttpServletRequest req, HttpServletResponse resp) {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setCharType(TYPE_ONLY_NUMBER);  // 纯数字
        String vcode = specCaptcha.text().toLowerCase();
        String key = captcha_key_suffix + CommonUtil.getUUID();
        redisUtil.setEx(key, vcode, 3, TimeUnit.MINUTES);

        JSONObject res = new JSONObject();
        res.put("key", key);
        res.put("image", specCaptcha.toBase64());
        return ResponseResult.ok("获取验证码操作成功", res);
    }


    @RequestMapping("/login")
    public ResponseResult login(@RequestBody String body) {
        logger.info(">>>>>>>>>>>>>> 登录接口入参: [{}]", body);
        JSONObject loginInfo = JSONObject.parseObject(body);
        String username = loginInfo.getString("username");
        String password = loginInfo.getString("password");
        String captchaId = loginInfo.getString("captchaId");
        String captcha = loginInfo.getString("captcha");

        XUser user = userService.getByUsernameAndPwd(username, password);
        if (user == null) {
            return ResponseResult.fail("用户名或密码错误");
        }
        Map<String, String> payload = new HashMap<>();
        payload.put("id", user.getId());
        payload.put("username", user.getUsername());
        String token = JWTUtil.getToken(payload);
        ResponseResult result;
        if (captchaId != null) {
            String redisCaptcha = redisUtil.get(captchaId);
            if (redisCaptcha != null && redisCaptcha.equals(captcha.trim().toLowerCase())) {
                // 登录成功后将用户信息和token返给前端
                JSONObject respData = new JSONObject();
                respData.put("userInfo", user);
                respData.put("token", token);
                result = ResponseResult.ok("登录成功!", respData);
            } else {
                result = ResponseResult.fail("验证码错误!");
            }
        } else {
            result = ResponseResult.fail("验证码为空!");
        }

        return result;
    }


    @RequestMapping("/test")
    public ResponseResult testToken(@RequestBody JSONObject params) {
        System.out.println("params = " + params);
        return ResponseResult.ok("测试请求成功", params);
    }





}
